import React, {useEffect, useState} from "react";
import {Layout, Menu} from "antd";
import {UserOutlined} from '@ant-design/icons'
import './index.css'
//withRouter作用: 把不是通过路由切换过来的组件中，将react-router 的 history、location、match 三个对象传入props对象上
import {withRouter} from "react-router-dom";
import axios from "axios";

const {Sider} = Layout
const {SubMenu} = Menu
// 图标数组
const iconList = {
    "/home": <UserOutlined/>,
    "/user-manage/list": <UserOutlined/>,
    "/right-manage/role/list": <UserOutlined/>,
    "/right-manage/right/list": <UserOutlined/>
}

function SideMenu(props) {
    const [menu, setMenu] = useState([])
    useEffect(async () => {
        const res = await axios.get('http://localhost:5000/rights?_embed=children')
        // console.log(res.data)
        setMenu(res.data)
    }, [])
    const {role: {rights}} = JSON.parse(localStorage.getItem("token"))
    // 检查是否有pagepermisson属性
    const checkPagePermission = (item) => {
        return item.pagepermisson && rights.includes(item.key)
    }
    // 渲染列表
    const renderMenu = (menuList) => {
        return menuList.map(item => {
            if (item.children?.length > 0 && checkPagePermission(item)) {
                return (<SubMenu key={item.key} icon={item.icon} title={item.title}>
                        {renderMenu(item.children)}
                    </SubMenu>
                )
            }
            return checkPagePermission(item) && <Menu.Item key={item.key} icon={iconList[item.key]} onClick={() => {
                props.history.push(item.key)
            }}>{item.title}</Menu.Item>
        })

    }
    const selectKeys = [props.location.pathname]
    const openKeys = ["/"+props.location.pathname.split("/")[1]]
    return (
        // <Sider trigger={null} collapsible collapsed={this.state.collapsed}>
        <Sider trigger={null} collapsible>
            <div style={{display: "flex", height: "100%", "flexDirection": "column"}}>
                <div className="logo">Global News Publishing System</div>
                <div style={{flex: 1, "overflow": "auto"}}>
                    <Menu theme="dark" mode="inline" defaultSelectedKeys={selectKeys} defaultOpenKeys={openKeys}>
                        {renderMenu(menu)}
                    </Menu>
                </div>
            </div>
        </Sider>
    )
}

export default withRouter(SideMenu)

//V6 路由版本中
/*
    const navigate = useNavigate()   然后再在onClick中写navigate(item.key)
 */
